<?php

namespace helper;

class CsvHelper
{

    /**
     * 导出csv表格
     * @param string $fileName 输出Excel表格文件名
     * @param array $headList 导出的Excel数据第一列表头
     * @param array $dataList 要导出的数组格式的数据
     * @param bool|string $download
     * @return void
     */
    static public function export(string $fileName, array $headList, array $dataList,$download=true){
        //set_time_limit(0);//防止超时
        //ini_set("memory_limit", "512M");//防止内存溢出
        if($download===true){ //浏览器下载
            header('Content-type:text/csv');
            header("Content-Disposition:attachment;filename={$fileName}.csv");
            header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
            header('Expires:0');
            header('Pragma:public');
            $fp = fopen('php://output', 'w');
        } else { //生成文件
            $path = 'upload/'.date('Ymd');
            Files::createDir($path);
            $fp = fopen("{$path}/{$fileName}.csv", 'w');
        }
        //表头中文转义
        foreach ($headList as $k => $v) {
            $headList[$k] = iconv("utf-8", "GBK//IGNORE", $v);
        }
        //将数据通过fputcsv写到文件句柄
        fputcsv($fp, $headList);
        //计数器
        $num = 0;
        //每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
        $limit = 10000;
        //逐行取出数据，不浪费内存
        $count = count($dataList);
        for ($i = 0; $i < $count; $i++) {
            $num++;
            //刷新一下输出buffer，防止由于数据过多造成问题
            if ($limit == $num) {
                ob_flush();
                flush();
                $num = 0;
            }
            $row = $dataList[$i];
            foreach ($row as $k => $v) {
                $row[$k] = iconv("utf-8", "GBK//IGNORE", $v);
            }
            fputcsv($fp, $row);
        }
        if (is_resource($fp)) fclose($fp);
    }

    /**
     * 读取csv文件
     * @param $fileName
     * @param int $start
     * @return array|string
     */
    static public function import($fileName,$start=1){
        $fp = fopen($fileName, "r");
        if(!$fp) return  '文件打开失败';
        $i = 0;
        $j = 0;
        $list = [];
        while($read = fgetcsv($fp)){
            if($i < $start){ //小于起始量则不读取,但$i仍然需要自增
                $i++;
                continue;
            }
            foreach ($read as $v) {
                $content = iconv("gbk","utf-8//IGNORE",$v);//转化编码;
                $list[$j][] = $content;
            }
            $i++;
            $j++;
        }
        if (is_resource($fp)) fclose($fp);
        return $list;
    }

}